package cn.wolfcode.service.impl;

import cn.wolfcode.common.domain.UserInfo;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.mapper.OrderInfoMapper;
import cn.wolfcode.mapper.PayLogMapper;
import cn.wolfcode.mapper.RefundLogMapper;
import cn.wolfcode.redis.SeckillRedisKey;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.service.ISeckillProductService;
import cn.wolfcode.util.IdGenerateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by wolfcode-lanxw
 */
@Service
public class OrderInfoSeviceImpl implements IOrderInfoService {
    @Autowired
    private ISeckillProductService seckillProductService;
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private PayLogMapper payLogMapper;
    @Autowired
    private RefundLogMapper refundLogMapper;

    @Override
    public String doSeckill(SeckillProductVo seckillProductVo, UserInfo user) {
        //扣除库存
        seckillProductService.decrStockCount(seckillProductVo);
        //生成秒啥订单
        String orderNo = this.createOrder(seckillProductVo,user);
        //记录用户下单标识
        String realKey = SeckillRedisKey.SECKILL_ORDER_SET.getRealKey(seckillProductVo.getTime() + "");
        redisTemplate.opsForSet().add(realKey,user.getPhone() + ":" + seckillProductVo.getId());
        return orderNo;
    }

    private String createOrder(SeckillProductVo vo, UserInfo user) {
        Date now = new Date();
        OrderInfo orderInfo = new OrderInfo();
        String orderNo = IdGenerateUtil.get().nextId() + "";//订单编号
        orderInfo.setOrderNo(orderNo);
        orderInfo.setUserId(user.getPhone());//用户ID
        orderInfo.setProductId(vo.getProductId());//商品ID
        orderInfo.setProductName(vo.getProductName());//商品名称
        orderInfo.setProductImg(vo.getProductImg());//商品图片
        orderInfo.setProductCount(vo.getCurrentCount());//商品总数
        orderInfo.setProductPrice(vo.getProductPrice());//商品原价
        orderInfo.setSeckillPrice(vo.getSeckillPrice());//秒杀价格
        orderInfo.setIntergral(vo.getIntergral());//消耗积分
        orderInfo.setStatus(OrderInfo.STATUS_ARREARAGE);//订单状态
        orderInfo.setCreateDate(now);//订单创建时间
        orderInfo.setSeckillTime(vo.getTime());// 秒杀场次
        orderInfo.setSeckillDate(vo.getStartDate());//秒杀的日期
        orderInfo.setProductId(vo.getId());//秒杀商品ID
        orderInfoMapper.insert(orderInfo);
        return orderNo;
    }
}
